<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 采用最新Thinkphp5助手函数特性实现单字母函数M D U等简写方式
 * ============================================================================
 * $Author: IT宇宙人 2015-08-10 $
 */
namespace app\api\controller;

use app\common\logic\CartLogic;
use app\common\logic\Integral;
use app\common\logic\CouponLogic;
use app\common\logic\Pay;
use app\common\logic\PlaceOrder;
use app\common\model\Combination;
use app\common\model\Goods;
use app\common\model\ShippingArea;
use app\common\model\SpecGoodsPrice;
use app\common\util\TpshopException;
use think\Controller;
use think\Page;
use think\Db;

class Cart extends Base
{

    public $cartLogic; // 购物车逻辑操作类

    /**
     * 析构流函数
     */
    public function  __construct()
    {
        parent::__construct();
        $this->cartLogic = new CartLogic(); 
        $this->cartLogic->setUserId($this->user_id);
        // 给用户计算会员价 登录前后不一样
        if ($this->user_id) {
            $user = DB::name('users')->where("user_id", $this->user_id)->find();
            $discount = (empty((float)$user['discount'])) ? 1 : $user['discount'];
            if ($discount != 1) {
                $c = Db::name('cart')->where(['user_id' => $user['user_id'], 'prom_type' => 0])->where('member_goods_price = goods_price')->count();
                $c && Db::name('cart')->where(['user_id' => $user['user_id'], 'prom_type' => 0])->update(['member_goods_price' => ['exp', 'goods_price*' . $discount]]);
            }
        }


    }

    /**
     * 将商品加入购物车
     */
    function addCart()
    {
        $goods_id = I("goods_id/d"); // 商品id
        $goods_num = I("goods_num/d");// 商品数量
        $item_id = I("item_id/d"); // 商品规格id
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        if(empty($goods_id)){
            $this->ajaxReturn(['status'=>0,'msg'=>'请选择要购买的商品','result'=>'']);
        }
        if(empty($goods_num)){
            $this->ajaxReturn(['status'=>0,'msg'=>'购买商品数量不能为0','result'=>'']);
        }
         
        $this->cartLogic->setGoodsModel($goods_id);
        $this->cartLogic->setUniqueId($unique_id);
        $this->cartLogic->setUserId($this->user_id);
        $this->cartLogic->setSpecGoodsPriceById($item_id);
        $this->cartLogic->setGoodsBuyNum($goods_num);
        try {
            $this->cartLogic->addGoodsToCart();
            $this->ajaxReturn(['status' => 1, 'msg' => '加入购物车成功','result'=>$this->cartLogic->getUserCartGoodsNum()]);
        } catch (TpshopException $t) {
            $error = $t->getErrorArr();
            $this->ajaxReturn($error);
        }
    }

    /**
     * 删除购物车的商品
     */
    public function delCart()
    {
        //字符串格式1,2,3
        $ids = I("ids"); // 商品 ids
        $idsArr = explode(',',$ids);
//        $result = M("Cart")->where("id","in", $ids)->delete(); // 删除id为5的用户数据
        // 查找购物车数量,xwy-2018-6-19
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        $this->cartLogic->setUserId($this->user_id);
        $result = $this->cartLogic->delete($idsArr);
        $cart_count = cart_goods_num(0, $unique_id);
        if ($result !== false) {
            $this->ajaxReturn(['status' => 1, 'msg' => '删除成功', 'result' => $cart_count]);// 返回结果状态(购物车数)
        } else {
            $this->ajaxReturn(['status' => 0, 'msg' => '删除失败', 'result' => $cart_count]);
        }
    }

    /**
     * ajax 将搭配购商品加入购物车
     */
    public function addCombination()
    {
        $combination_id = input('combination_id/d');//搭配购id
        $num = input('num/d');//套餐数量
        $combination_goodsData = htmlspecialchars_decode(input('combination_goods')) ;//套餐里的商品
//        halt($combination_goodsData);
        $combination_goods = json_decode($combination_goodsData, true); //app 端 json 形式传输过来
//        $combination_goods = json_decode(input('combination_goods')) ;//套餐里的商品
//        halt($combination_goods);
//        $combination_id = 14;
//        $num = 1;
//        $combination_goods = [
//            ['goods_id' => 143, 'item_id' => 0],
//            ['goods_id' => 144, 'item_id' => 0],
//        ];
        if (empty($combination_id)) {
            $this->ajaxReturn(['status' => 0, 'msg' => '参数错误']);
        }
        $cartLogic = new CartLogic();
        $combination = Combination::get(['combination_id' => $combination_id]);
        $cartLogic->setUserId($this->user_id);
        $cartLogic->setCombination($combination);
        $cartLogic->setGoodsBuyNum($num);
        try {
            $cartLogic->addCombinationToCart($combination_goods);
            $this->ajaxReturn(['status' => 1, 'msg' => '成功加入购物车']);
        } catch (TpshopException $t) {
            $error = $t->getErrorArr();
            $this->ajaxReturn($error);
        }
    }

    /*
     * 请求获取购物车列表
     */
    public function cartList()
    {
        $cart_form_data = $_POST["cart_form_data"]; // goods_num 购物车商品数量
        $cart_form_data = json_decode($cart_form_data, true); //app 端 json 形式传输过来
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        $where['session_id'] = $unique_id; // 默认按照 $unique_id 查询
        // 如果这个用户已经等了则按照用户id查询
        if($this->user_id){
            unset($where);
            $where['user_id'] = $this->user_id;
        } else {
            $this->ajaxReturn(['status' => 1, 'msg' => '获取成功', 'result' =>[]]);
//            $where['user_id'] = 0;
        }

       $cartList = M('Cart')->where($where)->getField("id,goods_num,selected,prom_type,prom_id,goods_id,goods_price,spec_key");
        if ($cart_form_data) {
            $updateData = [];
            // 修改购物车数量 和勾选状态
            foreach ($cart_form_data as $key => $val) {
                if (!isset($cartList[$val['cartID']])) {
                    continue;
                }
                $updateData[$key]['goods_num'] = $val['goodsNum']; 
                $updateData[$key]['selected'] = $val['selected'];
                $updateData[$key]['id'] = $val['cartID'];
                if ($cartList[$val['cartID']]['goods_num'] != $val['goodsNum']) {
                    $changeResult = $this->cartLogic->changeNum($val['cartID'], $val['goodsNum']);
                    if ($changeResult['status'] != 1) {
                        $this->ajaxReturn($changeResult);
                    }
                    break;
                } 
            }
            
            if ($updateData) {
                $this->cartLogic->AsyncUpdateCart($updateData);
            }
        }
        
        $this->cartLogic->setUniqueId($unique_id);
        $cartList = $this->cartLogic->getCartList(1);// 选中的商品
        //购物车价格列表
        $return['total_price'] = $this->cartLogic->getCartPriceInfo($cartList);
 
        if($return['total_price']){
            $return['total_price']['cut_fee'] = $return['total_price']['goods_fee'];
            $return['total_price']['num'] =$return['total_price']['goods_num'];
            unset($return['total_price']['goods_fee']);
            unset($return['total_price']['goods_num']);
        }

        $cartList = $this->cartLogic->getCartList(0);// 获取购物车所有商品
        foreach ($cartList as $k=>$v){
            $v['count_price'] = round(($v['goods_price'] - $v['member_goods_price']),2)*$v['goods_num'];
            $v['count_total_price'] = $v['member_goods_price']*$v['goods_num'];
            $v['count_num']= $v['goods_num'];
            foreach ($v['combination_cart'] as $kk=>$vv){
                if($vv['prom_type']==7){
                    $v['count_price'] += round(($vv['goods_price'] - $vv['member_goods_price']),2)*$vv['goods_num'];
                    $v['count_total_price'] += $vv['member_goods_price']*$vv['goods_num'];
                    $v['count_num'] += $vv['goods_num'];
                }
            }

        }

        $cart_count = 0;
        $cut_fee = 0;
        $total_price = 0;
        foreach($cartList as $cartKey=>$cart){
            $cart['store_count'] = $cart['goods']['store_count'];
//            $cart_count += $cart['goods_num'];//重新计算购物车数量
            $cart_count += $cart['count_num'];//计算购物车数量加上搭配购
//            halt($cart_count);

            if($cart['selected']){
                $cut_fee +=  $cart['count_price']?$cart['count_price']:0;//最多可省的价钱
                $total_price += $cart['count_total_price']?$cart['count_total_price']:0;//优惠后的价钱
            }
            unset($cart['goods']);
        }


        $return['total_price']['num'] = $cart_count;
        $return['total_price']['cut_fee'] = $cut_fee;
        $return['total_price']['total_fee'] = $total_price;
        $return['cartList'] = $cartList;
           
        $this->ajaxReturn(['status' => 1, 'msg' => '获取成功', 'result' =>$return]);
    }

    /**
     * 购物车第二步确定页面
     */
    public function cart2(){
        $goods_id = input("goods_id/d"); // 商品id
        $goods_num = input("goods_num/d");// 商品数量
        $item_id = input("item_id/d"); // 商品规格id
        $action = input("action"); // 行为
        if ($this->user_id == 0){
            $this->ajaxReturn(array('status'=>-1,'msg'=>'用户user_id不能为空','result'=>''));
        }
        $address_id = I('address_id/d');
        //获取地址
        if ($address_id) {
            $userAddress = M('UserAddress')->where(['user_id' => $this->user_id, 'address_id' => $address_id])->find();
        }
        if (!$address_id || !$userAddress) {
            $addresslist = M('UserAddress')->where("user_id = {$this->user_id}")->select();
            $userAddress = $addresslist[0];
            foreach ($addresslist as $address) {
                if ($address['is_default'] == 1) {
                    $userAddress = $address;
                    break;
                }
            }
        }

        if(empty($userAddress)){
            $this->ajaxReturn(['status' => -1, 'msg' => '请先添加收货地址', 'result' => null]);// 返回结果状态
        }else{
            $userAddress['total_address'] = getTotalAddress($userAddress['province'], $userAddress['city'], $userAddress['district'], $userAddress['twon'], $userAddress['address']);
        }

        $cartLogic = new CartLogic();
        $couponLogic = new CouponLogic();
        $cartLogic->setUserId($this->user_id);
        //立即购买
        if($action == 'buy_now'){
            $cartLogic->setGoodsModel($goods_id);
            $cartLogic->setSpecGoodsPriceById($item_id);
            $cartLogic->setGoodsBuyNum($goods_num);
            $buyGoods = [];
            try{
                $buyGoods = $cartLogic->buyNow();
            }catch (TpshopException $t){
                $error = $t->getErrorArr();
                $this->ajaxReturn($error);
            }
            $cartList['cartList'][0] = $buyGoods;
        }else{
            if ($cartLogic->getUserCartOrderCount() == 0){
                $this->ajaxReturn(['status'=>0,'msg'=>'你的购物车没有选中商品','result'=>'']);
            }
            $cartList['cartList'] = $cartLogic->getCartList(1); // 获取用户选中的购物车商品
        }
        $usersInfo = get_user_info($this->user_id);  // 用户
        $cartGoodsList = get_arr_column($cartList['cartList'],'goods');
        $cartGoodsId = get_arr_column($cartGoodsList,'goods_id');
        $cartGoodsCatId = get_arr_column($cartGoodsList,'cat_id');
        $cartPriceInfo = $cartLogic->getCartPriceInfo($cartList['cartList']);  //初始化数据。商品总额/节约金额/商品总共数量
        $userCouponList = $couponLogic->getUserAbleCouponList($this->user_id, $cartGoodsId, $cartGoodsCatId);//用户可用的优惠券列表
        $cartList = array_merge($cartList,$cartPriceInfo);
        $userCartCouponList = $cartLogic->getCouponAbleCartList($cartList, $userCouponList);
        $userCouponNum = count($userCartCouponList);
        $json_arr = array(
            'status'=>1,
            'msg'=>'获取成功',
            'result'=>array(
                'userAddress' =>$userAddress, // 收货地址
                'userCartCouponList'=>$userCartCouponList,  //优惠券
                'couponNum'=>$userCouponNum,  //用户可用的优惠券数量
                'cartList'=>$cartList['cartList'],
                'cartPriceInfo'=>$cartPriceInfo,//商品优惠总价
                'userInfo'    =>$usersInfo, // 用户详情
            ));
        $this->ajaxReturn($json_arr);
    }

    /**
     * ajax 获取订单商品价格 或者提交 订单
     */
    public function cart3(){
        if($this->user_id == 0){
            exit(json_encode(array('status'=>-100,'msg'=>"登录超时请重新登录!",'result'=>null))); // 返回结果状态
        }
        $address_id         = input("address_id/d"); //  收货地址id
        $invoice_title      = input('invoice_title');  // 发票
        $taxpayer           = input('taxpayer');       // 纳税人识别号
        $invoice_desc       = input('invoice_desc');       // 发票内容
        if($invoice_title == "" && $invoice_desc!="不开发票"){
            $invoice_title = "个人";
        }
        $coupon_id          = input("coupon_id/d"); //  优惠券id
        $pay_points         = input("pay_points/d",0); //  使用积分
        $user_money         = input("user_money/f",0); //  使用余额
        $user_note          = input("user_note",''); // 用户留言
        $pay_pwd             = input("payPwd",''); // 支付密码
        $goods_id           = input("goods_id/d"); // 商品id
        $goods_num          = input("goods_num/d");// 商品数量
        $item_id            = input("item_id/d"); // 商品规格id
        $action             = input("action"); // 立即购买
        mb_strlen($user_note,'utf-8') > 50 && exit(json_encode(['status'=>-1,'msg'=>"备注超出限制可输入字符长度！",'result'=>null]));
        if(!$address_id) exit(json_encode(array('status'=>-3,'msg'=>'请先填写收货人信息','result'=>''))); // 返回结果状态
        $address = Db::name('UserAddress')->where("address_id", $address_id)->find();
        $cartLogic = new CartLogic();
        $pay = new Pay();
        try {
            $cartLogic->setUserId($this->user_id);
            $pay->setUserId($this->user_id);
            if ($action == 'buy_now') {
                $cartLogic->setGoodsModel($goods_id);
                $cartLogic->setSpecGoodsPriceById($item_id);
                $cartLogic->setGoodsBuyNum($goods_num);
                $buyGoods = $cartLogic->buyNow();
                $cartList[0] = $buyGoods;
                $pay->payGoodsList($cartList);
            } else {
                $userCartList = $cartLogic->getCartList(1);
                $cartLogic->checkStockCartList($userCartList);
                $pay->payCart($userCartList);
            }
            $pay->delivery($address['district']);
            $pay->orderPromotion();
            $pay->useCouponById($coupon_id);
            $pay->useUserMoney($user_money);
            $pay->usePayPoints($pay_points);
            // 提交订单
            if ($_REQUEST['act'] == 'submit_order') {
                $placeOrder = new PlaceOrder($pay);
                $placeOrder->setUserAddress($address);
                $placeOrder->setInvoiceTitle($invoice_title);
                $placeOrder->setUserNote($user_note);
                $placeOrder->setTaxpayer($taxpayer);
                $placeOrder->setInvoiceDesc($invoice_desc);
                $placeOrder->setPayPsw($pay_pwd);
                $placeOrder->addNormalOrder();
                $cartLogic->clear();
                $order = $placeOrder->getOrder();
                $this->ajaxReturn(['status'=>1,'msg'=>'提交订单成功','result'=>$order['order_sn']]);
            }
            $this->ajaxReturn(['status'=>1,'msg'=>'计算成功','result'=>$pay->toArray()]);
        } catch (TpshopException $t) {
            $error = $t->getErrorArr();
            $this->ajaxReturn($error);
        }
    }

    public function cart4()
    {
        $order_sn = I('order_sn/s','');
        if (!$order_sn) {
            $this->ajaxReturn(['status' => -1, 'msg' => '非法操作！']);
        }
        $order = M('order')->field('order_sn,order_amount')->where(['order_sn' => $order_sn, 'user_id' => $this->user_id])->find();
        if (!$order) {
            $this->ajaxReturn(['status' => -1, 'msg' => '订单不存在']);
        }
        $this->ajaxReturn(['status' => 1, 'msg' => '获取成功', 'result' => $order]);
    }

    /**
     *  积分商品结算页 1
     * @return mixed
     */
    public function integral(){
        $goods_id = input('goods_id/d');
        $item_id = input('item_id/d');
        $goods_num = input('goods_num/d');
        $address_id = input('address_id/d');
        $isPointRate = tpCache('integral.is_point_rate');
        $isUseIntegral = tpCache('integral.is_use_integral');
        if ($isPointRate != 1 || $isUseIntegral != 1) {
            $this->ajaxReturn(['status' => 0, 'msg' => '商城暂时不能使用积分']);
        }
        if (empty($goods_id)) {
            $this->ajaxReturn(['status' => 0, 'msg' => '非法操作']);
        }
        if (empty($goods_num)) {
            $this->ajaxReturn(['status' => 0, 'msg' => '购买数不能为零']);
        }
        $goods = Goods::get(['goods_id' => $goods_id]);
        if (empty($goods)) {
            $this->ajaxReturn(['status' => 0, 'msg' => '该商品不存在']);
        }
        //获取地址
        if ($address_id) {
            $userAddress = M('UserAddress')->where(['user_id' => $this->user_id, 'address_id' => $address_id])->find();
        }
        if (!$address_id || !$userAddress) {
            $addresslist = M('UserAddress')->where(['user_id' => $this->user_id])->select();
            $userAddress = $addresslist[0];
            foreach ($addresslist as $address) {
                if ($address['is_default'] == 1) {
                    $userAddress = $address;
                    break;
                }
            }
        }
        if(empty($userAddress)){
            $this->ajaxReturn(['status' => -1, 'msg' => '请先添加收货地址', 'result' => null]);// 返回结果状态
        }else{
            $userAddress['total_address'] = getTotalAddress($userAddress['province'], $userAddress['city'], $userAddress['district'], $userAddress['twon'], $userAddress['address']);
        }

        if (empty($item_id)) {
            $goods_spec_list = SpecGoodsPrice::all(['goods_id' => $goods_id]);
            if (count($goods_spec_list) > 0) {
                $this->ajaxReturn(['status' => 0, 'msg' => '请传递规格参数']);
            }
            $goods_price = $goods['shop_price'];
            //没有规格
        } else {
            //有规格
            $specGoodsPrice = SpecGoodsPrice::get(['item_id' => $item_id, 'goods_id' => $goods_id]);
            if ($goods_num > $specGoodsPrice['store_count']) {
                $this->ajaxReturn(['status' => 0, 'msg' => '该商品规格库存不足，剩余' . $specGoodsPrice['store_count'] . '份']);
            }
            $goods_price = $specGoodsPrice['price'];
            $goods['item_id'] = $specGoodsPrice['item_id'];
            $goods['spec_key_name'] = $specGoodsPrice['key_name'];
        }
        $usersInfo = get_user_info($this->user_id);  // 用户
        //积分规则修改后的逻辑
        $point_rate = tpCache('integral.point_rate');

        //$point_rate = tpCache('shopping.point_rate');
        $data = [
            'userAddress'=>$userAddress,  //用户地址
            'point_rate' => $point_rate,  //积分比例
            'goods' => $goods,  //商品信息
            'goods_price' => $goods_price,  //商品价格
            'goods_num' => $goods_num,     //商品购买数量
            'userInfo'    =>$usersInfo, // 用户详情

        ];
        $this->ajaxReturn(['status' => 1, 'msg' => '获取成功', 'result' => $data]);
    }

    /**
     *  积分商品价格提交(计算价格)
     * @return mixed
     */
    public function integral2(){
        $goods_id           = input('goods_id/d');
        $item_id            = input('item_id/d');
        $goods_num          = input('goods_num/d');
        $address_id         = input("address_id/d"); //  收货地址id
        $user_note          = input('user_note'); // 给卖家留言
        $invoice_title      = input('invoice_title'); // 发票
        $taxpayer           = input('taxpayer'); // 发票纳税人识别号
        $invoice_desc       = input('invoice_desc');       // 发票内容
        if($invoice_title == "" && $invoice_desc!="不开发票"){
            $invoice_title = "个人";
        }
        $user_money         = input("user_money/f", 0); //  使用余额
        $pay_pwd             = input('pay_pwd');
        if (empty($address_id)){
            $this->ajaxReturn(['status' => -3, 'msg' => '请先填写收货人信息', 'result' => null]);
        }
        $integral = new Integral();
        $integral->setUserById($this->user_id);
        $integral->setGoodsById($goods_id);
        $integral->setSpecGoodsPriceById($item_id);
        $integral->setBuyNum($goods_num);
        $integral->setUserAddressById($address_id);
        $integral->useUserMoney($user_money);
        try{
            $integral->checkBuy();
            $pay = $integral->pay();
            // 提交订单
            if ($_REQUEST['act'] == 'submit_order') {
                $placeOrder = new PlaceOrder($pay);
                $placeOrder->setUserAddress($integral->getUserAddress());
                $placeOrder->setInvoiceTitle($invoice_title);
                $placeOrder->setUserNote($user_note);
                $placeOrder->setTaxpayer($taxpayer);
                $placeOrder->setInvoiceDesc($invoice_desc);
                $placeOrder->setPayPsw($pay_pwd);
                $placeOrder->addNormalOrder();
                $order = $placeOrder->getOrder();
                $this->ajaxReturn(['status'=>1,'msg'=>'提交订单成功','result'=>$order['order_sn']]);
            }
            $this->ajaxReturn(['status' => 1, 'msg' => '计算成功', 'result' => $pay->toArray()]);
        }catch (TpshopException $t){
            $error = $t->getErrorArr();
            $this->ajaxReturn($error);
        }

    }

    /**
     * 优惠券兑换
     */
    public function cartCouponExchange()
    {
        $coupon_code = input('coupon_code');
        $couponLogic = new CouponLogic;
        $return = $couponLogic->exchangeCoupon($this->user_id, $coupon_code);
        $this->ajaxReturn($return);
    }

    /**
     * 更新购物车，并返回计算结果
     */
    public function AsyncUpdateCart()
    {
        $cart = input('cart/a', []);
        $cartLogic = new CartLogic();
        $cartLogic->setUserId($this->user_id);
        $result = $cartLogic->AsyncUpdateCart($cart);
        $this->ajaxReturn($result);
    }
}
